import {
  Button,
  Form,
  Input,
  Image,
  Modal,
  Select,
  Cascader,
  InputNumber,
  message,
} from "antd";
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import ChooseProductBox from "./chooseProduct";
import {
  getUpProductByLabelId,
  getUpClassifyInfo,
  getUerList,
  getUserShopAddress,
  addOrder,
} from "../../../../utils/sendRequst";
import { getLabelFun } from "../../../../utils/js/dealFun";
const Edit = () => {
  const navigate = useNavigate();
  let [addOrderObj, setAddOrderObj] = useState({
    labelChild: "",
    orBuyerId: "",
    orNum: 1,
  });
  let [options, setOptions] = useState([]); //标签
  let [productArr, setProductArr] = useState([]); //标签下的商品列表
  let [userArr, setUserArr] = useState([]); //用户
  let [addressArr, setAddressArr] = useState([]); //用户下的地址
  let [productObj, setProductObj] = useState({ imgUrl: "error" });
  useEffect(() => {
    //获取可使用的标签
    getUpClassifyInfo().then((res) => {
      let aa = getLabelFun(null, res.data);
      setOptions(aa);
    });
    //获取用户
    getUerList().then((res) => {
      if ((res.code = 200)) {
        let arr = dealSelectData(res.data, "user_id", "user_name");
        setUserArr(arr);
      }
    });
  }, []);
  //下单人变化，则对应地址数组变化
  const changeBuyer = (val) => {
    getUserShopAddress({ user_id: val }).then((res) => {
      if ((res.code = 200)) {
        let arr = [];
        res.data.forEach((element) => {
          let obj = {};
          obj.value = element.address_id;
          obj.label =
            element.address_username +
            "/" +
            element.address_detailed +
            "/" +
            element.address_phone;
          arr.push(obj);
        });
        setAddressArr(arr);
      }
    });
    // setAddressArr(arr)
  };
  function dealSelectData(oldData, id, name) {
    let arr = [];
    oldData.forEach((element) => {
      let obj = {};
      obj.value = element[id];
      obj.label = element[name];
      arr.push(obj);
    });
    return arr;
  }
  //表单事件
  const onFinish = (values) => {
    let obj = { ...values };
    obj.productID = productObj.productID;
    obj.orPrice = obj.orNum * productObj.productPrice;
    obj.orStartTime = new Date();
    //发送请求，添加订单数据
    addOrder(obj).then((res) => {
      if (res.code == 200) {
        message.success("添加成功");
        navigate("/index/orderList");
      }
    });
  };
  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };
  //选择商品
  const chooseProduct = () => {
    let { labelChild } = addOrderObj;
    getUpProductByLabelId({ labelChild }).then((res) => {
      if (res.code == 200) {
        let arr = res.data.map((item) => {
          item.key = item.productID;
          return item;
        });
        setProductArr(arr);
        return arr;
      }
    });
    setIsModalOpen(true);
  };
  //模态框事件
  const [isModalOpen, setIsModalOpen] = useState(false);
  //关闭模态框
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  //选择标签变了
  const onChange = (value) => {
    let num = value.at(-1);
    let obj = { ...addOrderObj };
    obj.labelChild = num;
    setAddOrderObj(obj);
  };
  //选择优惠卷
  const handleYHChange = (val) => {
    console.log("handleYHChange", val);
  };
  //获取已选择的商品和商品图片
  function getProductInfo(data) {
    let obj = { ...addOrderObj };
    let src = "/api" + data.productUrl;
    obj.imgUrl = src;
    obj.productID = data.productID;
    obj.productPrice = data.productPrice;
    setProductObj(obj);
  }
  return (
    <div>
      <Modal
        title="Basic Modal"
        open={isModalOpen}
        onCancel={handleCancel}
        footer={null}
      >
        <ChooseProductBox
          productArr={productArr}
          getProductInfo={getProductInfo}
        ></ChooseProductBox>
      </Modal>
      <Form
        name="basic"
        labelCol={{
          span: 8,
        }}
        wrapperCol={{
          span: 16,
        }}
        style={{
          maxWidth: 600,
        }}
        initialValues={addOrderObj}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item
          name="label" //初始化动态变得数据
          label="商品标签"
        >
          <Cascader
            options={options}
            onChange={onChange}
            placeholder="请选择商品标签"
          />
        </Form.Item>
        <Form.Item label="请选择商品" name="productImg">
          <Image
            width={200}
            height={200}
            src={productObj.imgUrl}
            onClick={chooseProduct}
            preview={false}
            fallback=""
          />
        </Form.Item>

        <Form.Item label="商品数量">
          <Form.Item name="orNum" noStyle>
            <InputNumber min={1} max={10} />
          </Form.Item>
        </Form.Item>
        <Form.Item name="orBuyerId" label="下单人">
          <Select
            style={{
              width: 120,
            }}
            onChange={changeBuyer}
            allowClear
            options={userArr}
          />
        </Form.Item>
        <Form.Item name="orAddressId" label="收货人">
          <Select
            style={{
              width: 120,
            }}
            allowClear
            options={addressArr}
          />
        </Form.Item>
        <Form.Item
          wrapperCol={{
            offset: 8,
            span: 16,
          }}
        >
          <Button type="primary" htmlType="submit">
            确认购买
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default Edit;
